﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using Cheems.Service.Media;
using Cheems.Interface.Media;
using Cheems.Interface.Models.Media;

namespace Cheems.Control.Extensions
{
    public class ButtonExtensions
    {
        // 定义附加属性 IsSoundEnabled
        public static readonly DependencyProperty IsSoundEnabledProperty =
            DependencyProperty.RegisterAttached(
                "IsSoundEnabled",
                typeof(bool),
                typeof(ButtonExtensions),
                new PropertyMetadata(false, OnIsSoundEnabledChanged));

        // 获取附加属性 IsSoundEnabled
        public static bool GetIsSoundEnabled(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsSoundEnabledProperty);
        }

        // 设置附加属性 IsSoundEnabled
        public static void SetIsSoundEnabled(DependencyObject obj, bool value)
        {
            obj.SetValue(IsSoundEnabledProperty, value);
        }

        public static readonly DependencyProperty SoundTypeProperty =
            DependencyProperty.RegisterAttached(
                "SoundType",
                typeof(AudioLibrary),
                typeof(ButtonExtensions),
                new PropertyMetadata(AudioLibrary.btn_01));

        // 获取附加属性 IsSoundEnabled
        public static AudioLibrary GetSoundType(DependencyObject obj)
        {
            return (AudioLibrary)obj.GetValue(SoundTypeProperty);
        }

        // 设置附加属性 IsSoundEnabled
        public static void SetSoundType(DependencyObject obj, AudioLibrary value)
        {
            obj.SetValue(SoundTypeProperty, value);
        }


        // 当 IsSoundEnabled 属性发生变化时触发
        private static void OnIsSoundEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Button button && (bool)e.NewValue)
            {
                // 为按钮添加点击事件处理器
                button.Click += Button_Click;
            }
            else if (d is Button btn && !(bool)e.NewValue)
            {
                // 移除按钮的点击事件处理器
                btn.Click -= Button_Click;
            }
        }

        static ISound soundService = new SoundService();
        // 播放声音的逻辑
        private static async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                // 检查是否启用了声音播放
                bool isSoundEnabled = GetIsSoundEnabled(button);
                AudioLibrary soundType = GetSoundType(button);
                if (isSoundEnabled)
                {
                    await soundService.PlayFixedAudio(soundType);
                }
            }
        }

    }
}
